<template>
  <xy-page>
    <div class="livechannel clearfix">
      <div class="context">
        <el-form ref="form" :model="form" label-width="120px">
          <el-form-item label="直播名称" label-width="120px">
            <el-input v-model="form.liveName" class="w300" maxlength="30"></el-input>
          </el-form-item>
          <el-form-item label="直播开始时间" label-width="120px">
            <el-date-picker v-model="form.liveTime1" type="date" class="wd180" :picker-options="pickerOptions" @change="changeDate"></el-date-picker>
            <el-time-picker class="wd120" v-model="form.liveTime2" @change="changeTime"></el-time-picker>
          </el-form-item>
          <el-form-item label="关联主持人" label-width="120px">
            <el-input v-model="form.hostName" class="w300" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="频道号" label-width="120px">
            <el-input v-model="form.num" class="w300" disabled></el-input>
            <el-button type="text"  @click="setForbWords">严禁词设置</el-button>
          </el-form-item>
          <el-form-item label="频道密码" label-width="120px">
            <el-input v-model="form.pwd" class="w300" maxlength="16" minlength="5" placeholder="密码由5-16位由数字英文下划线组成"></el-input>
          </el-form-item>
          <el-form-item label="直播场景" label-width="120px">
            <el-input v-model="form.scenes" class="w100" disabled></el-input>
          </el-form-item>
          <el-form-item label="并发限制" label-width="120px">
            <el-input v-model="form.peoplenum" class="w300" maxlength="9" placeholder="最大不超过9位数字"></el-input>
          </el-form-item>
          <el-form-item label="讲师链接" label-width="120px" class="urls">
            <el-input v-model="form.url" class="w300" readonly></el-input>
            <el-button size="small" @click="openUrl(form.url)">打开</el-button>
            <el-button size="small" v-clipboard:copy="form.url" v-clipboard:success="onCopy" v-clipboard:error="onError">复制</el-button>
          </el-form-item>
          <el-form-item label="推流地址" label-width="120px" class="urls">
            <el-input v-model="form.adress" class="w300" readonly></el-input>
            <el-button size="small" v-clipboard:copy="form.adress" v-clipboard:success="onCopy" v-clipboard:error="onError">复制</el-button>
          </el-form-item>
          <el-form-item label="推流APP" label-width="120px" v-if="form.qrCode">
            <!-- <div class="qrcode2" ><div id="qrcode2" ref="qrcode"></div></div><div></div> -->
            <div class="pull-qrcode" :style="'background-image: url(' + form.qrCode + ')'" ></div>
          </el-form-item>
          <el-form-item label="所属管理员" label-width="120px" v-show="!(userType==2)">
            <el-input v-model="form.admin" class="w300" readonly></el-input>
            <el-button type="text" @click="updateAdmin">修改</el-button>
            <el-dialog title="修改管理员" :visible.sync="dialogTableVisible" :modal="false">
              <el-button size="small" @click="adddialog">添加</el-button>
              <el-table :data="gridData" style="height:300px;overflow:auto">
                <el-table-column property="admin" label="直播间管理员"></el-table-column>
                <el-table-column property="Relation" label="操作" width="120" align="center">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      v-if="gridData[scope.$index].iscurron==1"
                      @click="isRelation(scope)"
                    >取消关联</el-button>
                    <el-button
                      type="text"
                      v-else-if="gridData[scope.$index].iscurron==0"
                      @click="isRelation(scope)"
                    >关联</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-dialog>
            <el-dialog title="添加管理员" :visible.sync="isadddialog" :modal="false">
              <el-form-item label="邮箱">
                <el-input v-model="form.adminEmail"></el-input>
              </el-form-item>
              <el-form-item label="密码">
                <el-input v-model="form.adminPwd" minlength="5" maxlength="16" placeholder="密码长度为5~16，英文数字下划线"></el-input>
              </el-form-item>
              <el-form-item label="用户名">
                <el-input v-model="form.adminUser" maxlength="20" placeholder="最长20个字符"></el-input>
              </el-form-item>
              <el-form-item label=" ">
                <el-checkbox-group v-model="form.isRelated">
                  <el-checkbox label="关联到当前直播间" name="type"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <span slot="footer" class="dialog-footer">
                <el-button class="btn" @click="addAdmin">保存</el-button>
              </span>
            </el-dialog>
          </el-form-item>
          <el-form-item label label-width="100px">
            <el-button type="primary" @click="saveScene" min-width="60px">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="preview">
        <div class="mgt10 ">
          <div class="txtC">扫一扫观看直播</div>
          <div class="qrcode mgt10"><div id="qrcode" ref="qrcode"></div></div>
          <div class="mgt10">
            <el-input v-model="form.qrUrl" class="qrcode-url" readonly ></el-input>
            <el-button  class="mgt10" v-clipboard:copy="form.qrUrl" min-width="60px" v-clipboard:success="onCopy" v-clipboard:error="onError">复制</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="聊天严禁词设置" :visible.sync="isForbidDia" :before-close="beforeClose" class="forbDia">
      <el-input placeholder="搜索严禁词" class="forbidInput" v-model="searchWord" clearable @change="filForbWords">
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-button type="text" class="forbAddBtn">
        <a href="/static/Strictlyprohibit.xls" download="模板" style="text-decoration:none;">下载模板</a>
      </el-button>
      <el-upload action="/admin/instance/ccb/polyv/channel/badword/channelBadwordAddByExcel.do" :data="dataBody"
        :show-file-list="false"
        :headers="sessionKeyBody"
        class="forbAddBtn"
        :on-success="successUploadFile"
        :on-error="errorUploadFile">
      <el-button>批量添加</el-button>
      </el-upload>
      <el-button type="primary" class="forbAddBtn" @click="addForbWord">添加</el-button>
      <div class="forbTable">
        <xy-table :tableData="forbTableData" :loading="forbTableData.isLoading" :noEmpty="forbTableData.list.length==0?false:true">
          <el-table-column label="聊天室禁词" align="center" min-width="120">
            <template slot-scope="scope">
              <span v-show="scope.row.isSaved">{{scope.row.word}}</span>
              <el-input placeholder="限20个字符" v-show="!scope.row.isSaved" v-model="scope.row.word" class="rowInput" maxlength="20" clearable>{{scope.row.word}}</el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <div v-show="!scope.row.isSaved">
                <el-button type="text" @click="saveRow(scope.row)" :loading="scope.row.isSaving">保存</el-button>
                <el-button type="text" @click="cancelAdd(scope)">取消</el-button>
              </div>
              <div v-show="scope.row.isSaved">
                <el-button type="text" @click="delForbWord(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </xy-table>
      </div>
    </el-dialog>
  </xy-page>
</template>

<script>
export default {
  data() {
    return {
      dataBody:{},
      sessionKeyBody:{},
      sessionKey:'',
      tempList:[],
      searchWord:'',
      forbTableData:{
        isLoading:false,
        total:0,
        list:[]
      },
      isForbidDia:false,
      userType:'',
      pickerOptions:{
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      form: {
        liveName: '',
        liveTime1: '',
        liveTime2: '',
        hostName: '',
        num: '',
        pwd: '',
        scenes: '',
        peoplenum: '',
        admin: '',
        url: '',
        adress: '',
        adminEmail:'',
        adminPwd: '',
        adminUser: '',
        isRelated: false,
        teacher: '小屋',
        qrUrl:'',
        qrCode:''
      },
      dialogTableVisible: false,
      isadddialog: false,
      gridData: [],
      channelId: '',
      appId:'',
      loading:false,
      typeTitle:'',
    };
  },
  methods: {
    successUploadFile(res){
      if(res.success){
        this.$message.success('添加成功')
        this.getForbWords()
      }else{
        if(res.code == 50001){
          this.$message.error(res.message)
        }else{
          this.$message.error('添加失败')
        }
      }
    },
    errorUploadFile(){
      this.$message.error('添加失败')
    },
    //严禁词搜索
    filForbWords(){
      this.forbTableData.list =  this.tempList.filter((item)=>{
        if(item.word.indexOf(this.searchWord) != -1){
          return item
        }
      })
      //暂无数据文案
      if(!this.forbTableData.list.length){
        this.forbTableData.isLoading = true
        setTimeout(()=>{this.forbTableData.isLoading = false},1)
      }
    },
    setForbWords(){
      this.isForbidDia=true
      this.getForbWords()
    },
    changeDate(){
      if(this.form.liveTime2 == ''){
        this.form.liveTime2 = this.form.liveTime1
      }
      if(!this.form.liveTime1){
        this.form.liveTime2 = ''
      }
      this.$forceUpdate()
    },
    // 改变直播开始时间
    changeTime(){
      if(!this.form.liveTime1){
        this.form.liveTime2 = ''
        this.$message.warning('请先选择日期')
      }
      this.$forceUpdate()
    },
    beforeClose(){
      this.isForbidDia = false
      this.forbTableData.list = this.tempList.concat()
    },
    delForbWord(row){
      this.$confirm('此操作将永久删除该严禁词, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$postStream('/admin/instance/ccb/polyv/channel/badword/delete.do',{
          data:{
            appId:this.appId,
            words:row.word,
            channelId:this.channelId
          },
          success:(res)=>{
            if(res.success){
              this.$message.success('删除成功')
              this.getForbWords()
            }else{
              if(res.code == 50001){
                this.$message.error(res.message)
              }else{
                this.$message.error('删除失败')
              }
            }
          },
          error:()=>{
            this.$message.error('删除失败')
          }
        })
      })
    },
    getForbWords(){
      this.forbTableData.isLoading = true
      this.$postStream('/admin/instance/ccb/polyv/channel/badword/list.do',{
        data:{
          appId:this.appId,
          channelId:this.channelId
        },
        success:(res)=>{
          if(res.success){
            this.forbTableData.list = []
            this.form.forbidList = res.object.toString()
            this.forbTableData.total = res.object.length
            if(res.object.length){
              res.object.forEach(item=>{
                this.forbTableData.list.push({word:item,isSaved:true})
              })
            }
            this.tempList = this.forbTableData.list.concat()
          }else{
            this.$message.error('禁词获取失败')
          }
        },
        error:()=>{
          this.$message.error('禁词获取失败')
        },
        complete:()=>{
          this.forbTableData.isLoading = false
        }
      })
    },
    saveRow(row){
      if(!row.word.trim()){
        this.$message.error('禁词不能为空')
        return
      }
      row.isSaving = true
      this.$postStream('/admin/instance/ccb/polyv/common/badword/add.do',{
        data:{
          words:"['"+row.word.trim()+"']",
          appId:this.appId,
          channelId:this.channelId
        },
        success:(res)=>{
          if(res.success){
            this.$message.success('保存成功')
            this.getForbWords()
          }else{
            if(res.code == 50001){
              this.$message.error(res.message)
            }else{
              if(new Set(row.word).has("'")){
                this.$message.error('禁用词不能包含英文单引号')
              }else{
                this.$message.error('保存失败')
              }
            }
          }
        },
        error:()=>{
          this.$message.error('保存失败')
        },
        complete:()=>{
          row.isSaving = false
        }
      })
    },
    cancelAdd(scope){
      this.forbTableData.list.splice(scope.$index,1)
    },
    addForbWord(){
      this.forbTableData.list.unshift({word:'',disabled:false,isSaving:false})
    },
    onCopy(){//复制成功提示
      this.$message.success('复制成功!')
    },
    onError(){
      this.$message.error('复制失败!')
    },
    adddialog() {//添加的窗口
      this.dialogTableVisible = false
      this.isadddialog = true
    },
    updateType(item){
      if(!item){
        return 2
      }else{
        return 1
      }
    },
    isRelation(item) {//判断频道关联
      this.gridData[item.$index].iscurron = Number(!this.gridData[item.$index].iscurron)
      this.$postStream('/admin/instance/ccb/polyv/adminUser/channel/linkChannelAdmin.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId,
          email: item.row.admin,
          modifyType: this.updateType(this.gridData[item.$index].iscurron),
          page:1,
          displayRecord:10
        },
        success:res=>{
          if(res.success){
            this.typeTitle = ''
            if(this.updateType(this.gridData[item.$index].iscurron)==1){
              this.typeTitle='关联'
              this.form.admin = item.row.admin
            }else{
              this.typeTitle='取消关联'
              this.form.admin = '未绑定管理员'
            }
            this.$message.success(this.typeTitle+'成功!')
            this.dialogTableVisible = false
            // this.getContent()
          }else{
            this.$message.error(this.typeTitle+'失败!')
          }
        }
      })
    },
    saveScene() {//保存
      let dayTime=this.$utils.formatTime(new Date(this.form.liveTime1))
      let dateTime=this.$utils.formatDay(new Date(this.form.liveTime2))
      let showTime=new Date((dayTime+" "+dateTime)).getTime()
      if(showTime!=''&&showTime<new Date().getTime()){
        this.$message.error('直播时间不能小于当前时间')
        return
      }
      if(!this.form.pwd.trim()){
        this.$message.error('密码不能为空')
        return
      }else if(!this.$utils.identifyPwd(this.form.pwd)){
        this.$message.error('密码格式错误')
        return
      }
      if(!this.$utils.isQuantity(this.form.peoplenum)){
        this.$message.error('格式错误，只能输入数字')
        return
      }
      this.$postStream('/admin/instance/ccb/polyv/channel/updateSimpleSetting.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId,
          maxViewer: Number(this.form.peoplenum) ||0,
          name: this.form.liveName||'',
          password: this.form.pwd||'',
          publisher: this.form.hostName||'',
          scene: this.liveType(this.form.scenes)||'',
          startTime: showTime||0
        },
        success:res=>{
          if(res.success){
            this.$message.success('设置成功!')
            this.getContent()
          }else{
            this.$message.error(res.message)
          }
        }
      })
    },
    // 获取 code
    getCode(cb){
      this.$postStream('/admin/instance/ccb/polyv/channel/generateCode/get.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId
        },
        success:(res)=>{
          if(res.success){
            let code = res.object.token
            cb && cb(code)
          }
        }
      })
    },
    openUrl(url) { // 打开链接
      if(this.$utils.isHttp(url)){
        this.getCode((code)=> {
          this.$utils.linkTo(url + '&token=' + code)
        })
      }else{
        this.getCode((code)=> {
          this.$utils.linkTo('http://'+ url + '&code=' + code)
        })
      }
    },
    qrCode(index,qrUrl) { // 二维码
      let qrWidth =''
      let qrHeight = '' 
      if(index==2){
        qrWidth = 100
        qrHeight = 100
      }else{
        qrWidth = 200
        qrHeight = 200
      }
      this.$nextTick(()=>{
        const qrCode=document.getElementById('qrcode' + index)
        qrCode.innerHTML = ""
        new QRCode(qrCode, {
          width: qrWidth,//设置宽高  
          height: qrHeight,
          text: qrUrl
        })
      })
    },
    getContent(){//获取内容
      this.$postStream('/admin/instance/ccb/polyv/channel/sample.do',{
        data:{
          channelId: this.channelId,
          appId: this.appId
        },
        success: (res) => {
          if(res.object){
            this.form.liveName = res.object.name || ''
            this.form.liveTime1 = res.object.startTime || ''
            this.form.liveTime2 = res.object.startTime || ''
            this.form.hostName = res.object.publisher || ''
            this.form.num = res.object.channelId || ''
            this.form.pwd = res.object.channelPasswd || ''
            this.form.scenes = this.sceneType(res.object.scene) || ''
            this.form.peoplenum = res.object.maxViewer || 0
            this.form.admin = res.object.adminEmail || ''
            this.form.adress = res.object.pushUrl || ''
            // 这个链接没有错, 不用改, 本地没有这个页面是打不开的
            this.form.url = window.location.origin + '/html/teacher.html?channelId='+ res.object.channelId + '&appId='+ this.appId
            this.form.qrUrl = res.object.url || ''
            this.form.qrCode = res.object.qrCode || ''
            this.qrCode('', this.form.qrUrl) // 观看页二维码
            // this.qrCode(2, this.form.qrCode)
          }
        }
      })
    },
    updateAdmin(){//获取所属管理员列表
      this.dialogTableVisible = true
      this.form.adminEmail = ''
      this.form.adminPwd = ''
      this.form.adminUser = ''
      this.form.isRelated = false
      this.$postStream('/admin/instance/ccb/polyv/adminUser/channel/channelAdminList.do',{
        data:{
          appId: this.appId,
          channelId: this.channelId,
          page: 1,
          size: 10,
        },
        success:res=>{
          if(res.success){
            this.gridData = res.object.list.map(element=>{
              return{
                admin: element.email, 
                iscurron: element.isLinked
              }
            })
          }else{
            this.$message.error('获取管理员列表失败')
          }
        }
      })
    },
    addAdmin(){//添加保存管理员
      if (!this.form.adminEmail.trim()) {
        this.$message.warning("请输入邮箱")
        return
      } else if (!this.$utils.isEmail(this.form.adminEmail)) {
        this.$message.warning("请填写正确邮箱格式")
        return;
      }
      if (!this.form.adminPwd.trim()) {
        this.$message.warning("请输入密码")
        return;
      } else if (!this.$utils.identifyPwd(this.form.adminPwd)) {
        this.$message({
          message: "密码长度为5~16，英文数字下划线",
          type: "warning"
        });
        return;
      }
      if (!this.form.adminUser) {
        this.$message.warning("请输入用户名");
        return
      }
      
      this.$postStream('/admin/instance/ccb/polyv/adminUser/save.do',{
        data:{
          appId: this.appId,
          email: this.form.adminEmail,
          name: this.form.adminUser,
          passwd: this.form.adminPwd,
          type: 2
        },
        success:res=>{
          if(res.success){
            this.$postStream('/admin/instance/ccb/polyv/channel/sample.do',{
              data:{
                appId: this.appId,
                channelId: this.channelId,
                email: this.form.adminEmail,
                modifyType: this.switchVals(this.form.isRelated)
              },
              success:res=>{
                if(res.success){
                  this.$message.success('添加管理员成功!')
                  this.isadddialog = false
                  if(this.form.isRelated){
                    this.$postStream('/admin/instance/ccb/polyv/adminUser/channel/linkChannelAdmin.do',{
                      data:{
                        appId: this.appId,
                        channelId: this.channelId,
                        email: this.form.adminEmail,
                        modifyType: 1,
                        page:1,
                        displayRecord:10
                      },
                      success:res=>{
                        if(res.success){
                          this.dialogTableVisible = false
                          this.getContent()
                        }
                      }
                    })
                  }
                  this.updateAdmin()
                }else{
                  this.$message.error('添加失败!')
                }
              },
            })
          }else{
            this.loading = false
            this.$message.error(res.message)
          }
        },
        error: ()=>{
          this.loading = false
        }
      })
    }
  },
  mounted() {
    this.channelId = sessionStorage.getItem('channelId')
    this.userType = sessionStorage.getItem('userType')
    this.appId = sessionStorage.getItem('appId') || ''
    this.sessionKey = JSON.parse(sessionStorage.getItem('UserInfo')).sessionKey
    this.sessionKeyBody = {
      'session-key':this.sessionKey
    }
    this.dataBody = {
      channelId:this.channelId,
      appId:this.appId
    }
    this.getContent()
  }
};
</script>
<style lang="scss">
.forbidInput{
  width:30%;
  height: 34px !important;
  input{
    height: 34px !important;
  }
}
.rowInput{
  width:100% !important;
  input{
    height: 34px;
    margin:2px 0;
  }
}
.forbTable>div>div:nth-last-of-type(1){
  display:none;
}
.forbTable>div>div:nth-last-of-type(2){
  margin-bottom:0px !important;
}
.forbDia>div{
  margin-top:8vh;
}
.forbTable{
  margin-top:10px;
  max-height:54vh;
  overflow-y: auto;
}
</style>
<style lang="scss" scoped>
#fileInput{
  display:block;
  float:right;
  border-radius: 4px;
  height: 34px !important;
  line-height: 34px !important;
  width: 75px !important;
}
.forbAddBtn{
  float:right;
  margin-left:10px;
}
.attachTitle{
  color:#999;
}
.forbidSet{
  position:absolute;
  bottom:0px;
  height:25px;
  padding-left:10px;
}
.livechannel {
  position: relative;
  width: 100%;
  display: inline-block;
  .dialog-footer {
    text-align: center;
  }
  .wd120 {
    width: 120px;
    display: inline-block;
  }
  .wd180 {
    width: 180px;
    display: inline-block;
  }
  .context{
    display: inline-block;
  }
  .preview {
    float: right;
    right: 0;
    background: #ccc;
    text-align: center;
    width: 310px;
    height: 380px;
    .qrcode-url{
      margin-left: 35px;
      display: block;
      width: 243px;
    }
  }
  .qrcode{
    width: 240px;
    height: 240px;
    background: #fff;
    margin: 10px auto;
    border: 20px solid #fff;
  }
  .qrcode2{
    width: 100px;
    height: 100px;
    background: #fff;
  }
  .pull-qrcode{
    display: inline-block;
    width: 100px;
    height: 100px;
    background-size: 100%;
    background-position: center center;
    background-repeat: no-repeat;
    border: 1px solid #ccc;
    border-radius:4px;
  }
  .pull-qrcode-big{
    width: 300px;
    height: 300px;
    background-size: 100%;
    background-position: center center;
    background-repeat: no-repeat;
    border: 1px solid #ccc;
  }
}
</style>
<style lang="scss">
.urls .el-button--small{
  height:40px;
}
</style>
